/*
 * $Id: AuditedObject.java 1096 2011-07-04 03:36:31Z jyang $
 * 
 * Copyright (c) 2001-2008 Accentrix Company Limited. All Rights Reserved.
 */
package com.lightsaber.trade.core.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lightsaber.trade.core.common.util.CurrentUser;

@MappedSuperclass
public class AuditedObject implements Serializable {

    private final static Logger log = LoggerFactory.getLogger(AuditedObject.class);

    public static final long serialVersionUID = -7542985296161179894L;

    public static final String CREATED_BY = "createdBy";

    public static final String CREATED_DATE = "createdDate";

    public static final String LAST_UPDATED_BY = "lastUpdatedBy";

    public static final String LAST_UPDATED_DATE = "lastUpdatedDate";

    @Column(name = "CREATED_BY", nullable = true, length = 45, updatable = false)
    protected String createdBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATED_DATE", nullable = true, updatable = false)
    protected Date createdDate;

    @Column(name = "LAST_UPDATED_BY", length = 45)
    protected String lastUpdatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "LAST_UPDATED_DATE")
    protected Date lastUpdatedDate;

    @PrePersist
    @PreUpdate
    public void updateAuditInfo() {
        log.info("updating Audit Info, current user: {}", CurrentUser.getName());
        Date now = new Date();
        if (createdBy == null) {
            setCreatedBy(CurrentUser.getName());
            setCreatedDate(now);
        } else {
            setLastUpdatedBy(CurrentUser.getName());
            setLastUpdatedDate(now);
        }
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(final String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(final Date createdDate) {
        this.createdDate = createdDate;
    }

    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(final String lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

    public Date getLastUpdatedDate() {
        return lastUpdatedDate;
    }

    public void setLastUpdatedDate(final Date lastUpdatedDate) {
        this.lastUpdatedDate = lastUpdatedDate;
    }

    // @Override
    // public String toString() {
    // return ToStringBuilder.reflectionToString(this);
    // }
}
